package com.mrzhou.auth.config;

import com.mrzhou.auth.support.CloudJwtTokenEnhancer;
import com.mrzhou.core.tool.constants.TokenConstant;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

/**
 * JwtTokenStore配置
 *  @ConditionalOnProperty注解的说明:
 *      从application.yml中读取前缀为mrzhou.security.oauth2中包含的store-type
 *      的值; 如果值等于jwt这配置生效, 不等于此配置不生效;
 *      matchIfMissing: 如未读取到上诉配置中的值, 则默认为true;也就是此配置生效
 */
@Configuration
@ConditionalOnProperty(prefix = "spring.security.oauth2", name = "store-type", havingValue = "jwt", matchIfMissing = true)
public class JwtTokenStoreConfiguration {

    /**
     * 使用jwtTokenStore存储token信息
     */
    @Bean
    public TokenStore jwtTokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    /**
     * 用以生成jwt
     * @return
     */
    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(TokenConstant.SIGN_KEY);
        return converter;
    }

    /**
     * 扩展jwt返回的结果
     */
    @Bean
    @ConditionalOnMissingBean(name = "jwtTokenEnhancer")
    public TokenEnhancer jwtTokenEnhancer(){
        return new CloudJwtTokenEnhancer();
    }

}
